/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL || head->next == NULL) {
            return head;
        }
        int n = 0;
        ListNode *cur = head;
        ListNode *tail = NULL;

        while (cur) {
            ++n;
            tail = cur;
            cur = cur->next;
        }
        k %= n;
        if (k == 0) {
            return head;
        }

        ListNode* firstTail = NULL;
        cur = head;
        for (int i = 0; i < n - k; ++i) {
            firstTail = cur;
            cur = cur->next;
        }

        // [head, firstTail], [firstTail + 1, tail]
        ListNode *newHead = firstTail->next;
        tail->next = head;
        firstTail->next = NULL;
        return newHead;
    }
};
